package com.mvd.app.activitys;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.github.gcacace.signaturepad.views.SignaturePad;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.activity.BaseActivity;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.ImageUtils;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SignatureActivity extends BaseActivity {

    //    @BindView(R.id.view_signature)
    SignaturePad viewSignature;
    @BindView(R.id.btn_clear)
    Button btnClear;
    @BindView(R.id.btn_save)
    Button btnSave;
    private SignatureActivity instances = null;
    CarsInforModel carsInforModel;
    String line = "1";
    int type = 1;
    String my_PhotoType = "F101";
    private String Login_name = "";//当前登录的检测员的名字
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signature);
        ButterKnife.bind(this);
        instances = this;
        String logStrf = "\n" + "onCreate-----手写签字---SignatureActivity-----" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        carsInforModel = (CarsInforModel) getIntent().getSerializableExtra
                ("sign_carsInforModel");
        Login_name = getIntent().getExtras().getString("login_w_name", "");
        line = getIntent().getStringExtra("line");
        type = getIntent().getIntExtra("type", 1);
//        intent3.putExtra("line", includeAnWaijianchedao.getText().toString().trim());
//        intent3.putExtra("type", 1);
        switch (type) {
            case 1:
                my_PhotoType = "F101";
                break;
            case 2:
                my_PhotoType = "DC01";
                break;
            case 3:
                my_PhotoType = "C101";
                break;
        }


        viewSignature = (SignaturePad) findViewById(R.id.view_signature);
        viewSignature.setOnSignedListener(new SignaturePad.OnSignedListener() {

            @Override
            public void onStartSigning() {
                //Event triggered when the pad is touched
            }

            @Override
            public void onSigned() {
                //Event triggered when the pad is signed

            }

            @Override
            public void onClear() {
                //Event triggered when the pad is cleared

            }
        });
//        viewSignature.setMaxWidth();
    }


    @OnClick({R.id.view_signature, R.id.btn_clear, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_signature:
                break;
            case R.id.btn_clear:
//                viewSignature.clear();
                viewSignature.clear();
                break;
            case R.id.btn_save:
//                Bitmap bitmap = viewSignature.getBitMap();
                String filePath = Environment.getExternalStorageDirectory() + "/PDALogs/";
                String path = filePath + System.currentTimeMillis() + ".jpg";

                try {
//                    viewSignature.save(path,false,1);
                    Bitmap bitmap = viewSignature.getSignatureBitmap();
                    ImageUtils.saveBitmapFile(bitmap, path);

//                    BitmapFactory.Options options = new BitmapFactory.Options();
//                    options.inSampleSize = 2;
//                    Bitmap  bm = BitmapFactory.decodeFile(path, options);
//                    ImageUtils.saveBitmapFile(bm, path);
                    UtilsLog.e("imgPath===" + path);

                    getDataUploadPhoto(new File(path));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    //上传照片
    private void getDataUploadPhoto(final File file) {
        UtilsLog.e("手写签字---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO);
        String car_no = "";
//        if (SharedPreferencesUtils.getAddress(instances).equals("温州")) {
//            car_no = carsInforModel.getPlateRegion()
//                    + carsInforModel.getPlateNO()
//                    + carsInforModel.getPlateExtra();
//        } else if (SharedPreferencesUtils.getAddress(instances).equals("常山")) {
        car_no = carsInforModel.getPlateRegion()
                + carsInforModel.getPlateNO();
        String str = "QueueID:" + carsInforModel.getQueueID() + "\n" +
                "GUID:" + carsInforModel.getGUID() + "\n" +
                "Times:" + carsInforModel.getTimes() + "\n" +
                "PlatformSN:" + carsInforModel.getPlatformSN() + "\n" +
                "SN:" + carsInforModel.getSN() + "\n" +
                "PhotoDate:" + DateUtil.currentTime2() + "\n" +
                "PhotoType:" + my_PhotoType + "\n" +
                "Type:" + carsInforModel.getType() + "\n" +
                "CarNO:" + car_no + "\n" +
                "PlateType:" + carsInforModel.getPlateType() + "\n" +
                "ItemCode:" + "F1" + "\n" +
                "Line:" + line + "\n" +
                "VIN:" + carsInforModel.getVIN() + "\n" +
                "AppearanceInspector:" + Login_name + "\n" +
                "FileType:" + "jpg" + "\n";
        UtilsLog.e("手写签字---json==" + str);

        String logStr = "\n" + "手写签字---外检上传照片---json==" +
                "\n" + "json::" + str + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO).tag(instances)
                .params("AppearanceInspector", Login_name)
                //guid
                .params("QueueID", carsInforModel.getQueueID())
                //guid
                .params("GUID", carsInforModel.getGUID())
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                //SN
                .params("SN", carsInforModel.getSN())
                //拍摄时间
                .params("PhotoDate", DateUtil.currentTime2())
                //照片类型-拍的哪里的照片，位置
//                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
                .params("PhotoType", my_PhotoType)

                //车辆类型
                .params("Type", carsInforModel.getType())
                //车牌号码，两个拼起来的
                .params("CarNO", car_no)
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //拍照code F1表示外检
                .params("ItemCode", "F1")
                //外检车道，检测线代号
                .params("Line",line)
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                .params("FileType", "jpg")
//                .params("FileType", FileUtils.getExtensionName(file.getName()))
                //照片
                .params("zp", file)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("手写签字-result==" + result);

                        String logStr = "\n" + "手写签字--请求成功" +
                                "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("手写签字-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
//                                Intent intent=new Intent(instances, An_Huan_HomeActivity.class);
                                Intent intent = new Intent();
                                intent.putExtra("isSign", 1);
                                setResult(876,intent);
                                finish();
                            } else {
                                Toast.makeText(instances, "上传签名失败，请重试", Toast.LENGTH_LONG).show();
                            }
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("手写签字-onError==" + response.body());
                        UtilsLog.e("手写签字-onError==" + response.getException());
                        String logStr = "\n" + "手写签字-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_PHOTO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, "上传签名失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

}
